<template>
  <div v-if="haveImage" ref="container" class="image-container" @mouseover="showPreview = true"
    @mouseout="showPreview = false">
    <div ref="wrapper" class="image-wrapper" :style="{ '--width': width, '--height': height }">
      <img :src="placeholderImage" alt="Displayed Image" class="image" ref="image" @load="imageLoaded">
    </div>
  </div>
  <div v-else>
    <slot title="empty"></slot>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import devURL from '../Config/NetBaseConfig.js'

const props = defineProps({
  imageUrl: {
    type: String,
    required: true
  },
  placeholderImage: {
    type: String,
    default: '' // 默认占位图片URL
  },
  width: {
    type: String,
    default: '200px' // 默认宽度为 200 像素
  },
  height: {
    type: String,
    default: '200px' // 默认高度为 200 像素
  }
});

const container = ref(null);
const wrapper = ref(null);
const image = ref(null);
const showPreview = ref(false);
let haveImage = ref(true)

onMounted(() => {
  const options = {
    root: null,
    rootMargin: '0px',
    threshold: 0.1 // 当图片至少 10% 进入视口时触发回调
  };

  if (props.imageUrl == '') {
    haveImage.value = false
  }
  const observer = new IntersectionObserver(handleIntersection, options);
  observer.observe(image.value);
});


const handleIntersection = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      loadImage();
      observer.unobserve(entry.target);
    }
  });
};

const loadImage = () => {
  image.value.src = `${devURL}${props.imageUrl}`;
};


</script>

<style scoped>
.image-container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.image-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: var(--width);
  height: var(--height);
}

.image {
  max-width: 100%;
  max-height: 100%;
}

.preview {
  display: none;
  /* 初始隐藏 */
  position: absolute;
  border: 1px solid #ccc;
  /* 预览框边框样式 */
  background-repeat: no-repeat;
  background-size: cover;
  z-index: 999;
  pointer-events: none;
  /* 避免干扰鼠标事件 */
  background-image: var(--bg-image);
}

.image-container:hover .preview {
  display: block;
  /* 鼠标悬停时显示 */
  width: auto;
  /* 根据鼠标位置动态设置宽高 */
  height: auto;
  /* 根据鼠标位置动态设置宽高 */
  max-width: 200px;
  /* 设置最大宽度 */
  max-height: 200px;
  /* 设置最大高度 */
}
</style>